<?php
// get the current time. Used to tell how long it took.
// $start = microtime(true);

// Attempt to connect to the mySQL server
if(!(mysql_connect("localhost","625561_javaking","saint dain11")))
{
	// if it failed, die with an error message.
	die(json_encode("ERROR: COULD NOT CONNECT TO SERVER. CHECK YOUR INTERNET CONNECTION."));
}

// Attempt to select the proper database.
if(!mysql_select_db("javaking_clanteam_humansvszombies"))
{
	// if it failed, die with an error message.
	die(json_encode("ERROR: COULD NOT SELECT DATABASE"));
}

// Adjust the _REQUEST params. Will describe in function comment.
fixFields();

// Switch based off what mode was sent and call an appropriate function.
switch($_REQUEST['mode'])
{
case "READ":
	read_users($id, $barcode, $username, $usertype, $status);
	break;
case "ADD_USER":
	add_user($barcode, $username, $usertype);
	break;
case "REMOVE_USER":
	remove_user($barcode, $username);
	break;
case "MODIFY_INFO":
	modifyInfo($id, $barcode, $username, $usertype, $status);
	break;
case "KILL":
	kill($barcode, $username);
	break;
case "RESURRECT":
	resurrect($barcode, $username);
	break;
case "KILLCODE_ASSIGN":
	killcode_assign($barcode, $username, $killcode);
	break;
case "KILLCODE_ACQUIRE":
	killcode_acquire($barcode, $username, $killcode);
	break;
case "EXECUTE_SQL":
	execute_sql($_REQUEST['sql']);
default:
	echo json_encode("ERROR: UNKNOWN ACTION REQUESTED");
	break;
}

// Print how long it took
//echo "\n\n" . sprintf("time elapsed:%f",microtime(true)-$start);

function read_users($id, $barcode="barcode", $username="username", $usertype="usertype",
		$status="status", $killcodes_assigned="killcodes_assigned", $killcodes_acquired="killcodes_acquired")
{
	//printf("id:%s barcode:%s username:%s usertype:%s status:%s\n",$id, $barcode, $username, $usertype, $status);
	$sql = sprintf("SELECT * FROM hvz_users WHERE id=%s && barcode=%s && " .
		"username=%s && usertype=%s && status=%s && killcodes_assigned=%s && killcodes_acquired=%s",
		$id, $barcode, $username, $usertype, $status, $killcodes_assigned, $killcodes_acquired);
	//echo $sql."\n";
	executeSQL($sql);
	
}

function add_user($barcode, $username, $usertype)
{
	if ($usertype!="usertype")
	{
		$sql = sprintf("INSERT INTO hvz_users (barcode, username, usertype)
						VALUES (%s,%s,%s)",$barcode,$username,$usertype);
	}
	else 
	{
		$sql = sprintf("INSERT INTO hvz_users (barcode, username)
						VALUES (%s,%s)",$barcode,$username);
	}
	
	executeSQL($sql);
}

function remove_user($barcode="barcode", $username)
{
	$sql = sprintf("DELETE FROM hvz_users WHERE barcode=%s&&username=%s",$barcode, $username);
	//echo $sql."\n";
	
	executeSQL($sql);
}

function modifyInfo($id, $barcode, $username, $usertype, $status)
{
	$sql = sprintf("UPDATE hvz_users ".
					"SET barcode=%s, username=%s, usertype=%s, status=%s ".
					"WHERE id=%s",$barcode, $username, $usertype, $status, $id);
					
	//echo $sql."\n";
	executeSQL($sql);
}

function kill($barcode, $username)
{
	//printf("SELECT id FROM hvz_users WHERE barcode=%s username=%s",$barcode, $username);
	$result = mysql_query(sprintf("SELECT id FROM hvz_users WHERE barcode=%s&&username=%s", $barcode, $username));
	$row = mysql_fetch_array($result);
	modifyInfo($row['id'], $barcode, $username, $GLOBALS['usertype'], "\"ZOMBIE\"");
}

function resurrect($barcode, $username)
{
	$result = mysql_query(sprintf("SELECT id FROM hvz_users WHERE barcode=%s&&username=%s",$barcode, $username));
	$row = mysql_fetch_array($result);
	modifyInfo($row['id'], $barcode, $username, $GLOBALS['usertype'], "\"HUMAN\"");
}

function killcode_assign($barcode, $username, $killcode)
{
	$sql = sprintf("UPDATE hvz_users SET killcodes_assigned=".
		"CONCAT(killcodes_assigned,%s,\";\") WHERE barcode=%s&&username=%s",
		$killcode, $barcode, $username);
		
	executeSQL($sql);
}

function killcode_acquire($barcode, $username, $killcode)
{
	$sql = sprintf("UPDATE hvz_users SET killcodes_acquired=".
		"CONCAT(killcodes_acquired,%s,\";\") WHERE barcode=%s&&username=%s",
		$killcode, $barcode, $username);
		
	executeSQL($sql);
}




/* These are some random utility functions */

function executeSQL($sql)
{
	$q = mysql_query($sql);
	
	$error = mysql_error();
	if ($error) die(json_encode(array("ERROR" => $error)));
	
	if ($q!=1)
	{
		while ($e=mysql_fetch_assoc($q))
		{
			$output[] = $e;
		}
		array_unshift($output, array("SUCCESS" => $sql));
	} else {
		$output = array("SUCCESS" => "Query did not return any results.");
	}
	
	echo json_encode($output);
}

function fixFields()
{
	// make all the variables we'll be using global
	global $id, $barcode, $username, $usertype, $status, $killcode;
	$id = $_REQUEST['id'];
	$barcode = $_REQUEST['barcode'];
	$username = $_REQUEST['username'];
	$usertype = $_REQUEST['usertype'];
	$status = $_REQUEST['status'];
	$killcode = $_REQUEST['killcode'];
	
	// Now we check to see if the user even applied the field. If not, make it the column
	// name so that it will match all. If so, ensure that the data is surrounded by quotes
	// so that it satisfies the SQL syntax
	if($id=="") $id="id";
	else $id = ensureQuotes($id);
	
	if($barcode=="") $barcode="barcode";
	else $barcode = ensureQuotes($barcode);
	
	if($username=="") $username="username";
	else $username = ensureQuotes($username);
	
	if($usertype=="") $usertype="usertype";
	else $usertype = ensureQuotes($usertype);
	
	if($status=="") $status="status";
	else $status = ensureQuotes($status);
	
	$killcode = ensureQuotes($killcode);
}

function ensureQuotes($string)
{
	if(!startsWith($string,"\"")) $string = "\"".$string;
	if(!endsWith($string,"\"")) $string = $string."\"";
	return $string;
}

function startsWith($haystack,$needle)
{
    return strpos($haystack, $needle) === 0;
}



function endsWith($haystack,$needle)
{
  $expectedPosition = strlen($haystack) - strlen($needle);
  return strrpos($haystack, $needle, 0) === $expectedPosition;
}
?>